<template>
  <page-header-wrapper>
    <page-tab-list></page-tab-list>
    <a-card :bordered="false">
      <div style="display: flex; justify-content: flex-end; margin-bottom: 16px">
        <div>
          <a-button type="primary" @click="onAdd" icon="plus">新建任务</a-button>
        </div>
      </div>
      <a-alert message="同步任务会删除同步到的店铺的商品和活动等，请谨慎操作！" banner />
      <s-table rowKey="id" size="default" :columns="columns" :data="loadData" ref="table">
        <div slot="toStores" slot-scope="text, record">
          <a-tag v-for="(item, index) of record.to_store_names" :key="index">{{ item.name }}({{ item.id }})</a-tag>
        </div>
        <span slot="action" slot-scope="record">
          <a-button type="link" @click="onEdit(record)" size="small">编辑</a-button>
          <a-divider type="vertical" style="margin: 0 1px" />
          <a-button type="link" @click="onExe(record)" size="small">执行</a-button>
          <a-divider type="vertical" style="margin: 0 1px" />
          <a-popconfirm title="确认删除任务吗？" @confirm="onRemove(record)">
            <a-button type="link" size="small">删除</a-button>
          </a-popconfirm>
        </span>
      </s-table>
      <a-modal
        title="添加任务"
        style="width: 500px"
        v-model="visible"
        @ok="onOk"
        :destroyOnClose="true"
        :confirmLoading="loading"
      >
        <a-form-model ref="modalForm" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
          <a-form-model-item label="来源店铺" prop="from_store_id">
            <a-select v-model="form.from_store_id" placeholder="请选择来源店铺" allowClear show-search>
              <a-select-option :value="item.id" v-for="item in storeList" :key="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="被同步店铺" prop="to_store_ids" v-if="storeList.length > 0">
            <a-button type="primary" block @click="onSelectStore"> 选择店铺 </a-button>
            <div v-if="currentItem">
              <a-tag v-for="(item, index) of currentItem.to_store_names" :key="index"
                >{{ item.name }}({{ item.id }})</a-tag
              >
            </div>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </a-card>
    <ToolsStore
      :selectedList="currentItem ? currentItem.to_store_names : []"
      :checkList="currentItem ? currentItem.to_store_ids : []"
      @onOk="selectStore"
      ref="toolsStore"
    ></ToolsStore>
  </page-header-wrapper>
</template>

<script>
import { getList, getStoreList, saveData, delData, exeData } from '@/api/storeSync'
import { STable } from '@/components'
import ToolsStore from '@/components/tools/tools-store.vue'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '来源店铺',
    dataIndex: 'from_store_name',
    key: 'from_store_name',
  },
  {
    title: '同步到店铺',
    scopedSlots: { customRender: 'toStores' },
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'StoreSync',
  components: {
    STable,
    ToolsStore,
  },
  data() {
    return {
      loading: false,
      visible: false,
      columns,
      loadData: (parameter) => {
        return getList({
          ...parameter,
        })
          .then((res) => {
            return res.data
          })
          .catch(() => {
            this.$refs.table.localLoading = false
          })
      },
      rules: {
        from_store_id: [{ required: true, message: '请选择来源店铺', trigger: 'change' }],
        to_store_ids: [{ required: true, message: '请选择被同步店铺', trigger: 'change' }],
      },
      form: {
        id: 0,
        from_store_id: '',
        to_store_ids: '',
      },
      storeList: [],
      currentItem: null,
      isNew: false,
    }
  },
  mounted() {
    getStoreList().then((res) => {
      if (res.code == 0) {
        this.storeList = res.data
      }
    })
  },
  watch: {},
  computed: {},
  methods: {
    onAdd() {
      this.isNew = true
      this.visible = true
      this.currentItem = {
        to_store_ids: [],
        to_store_names: [],
      }
    },
    onChange(value) {
      this.form.to_store_ids = value
    },
    onEdit(item) {
      this.isNew = false
      this.form.from_store_id = item.from_store_id
      this.form.to_store_ids = item.to_store_ids
      this.form.id = item.id
      this.currentItem = item
      this.visible = true
    },
    onExe(item) {
      this.$confirm({
        title: '提示',
        content: '确定执行吗？',
        onOk: () => {
          const hide = this.$message.loading('操作中...')
          exeData({ id: item.id })
            .then((res) => {
              if (res.code == 0) {
                this.$message.success(res.msg)
                this.$refs.table.refresh(1)
              } else {
                this.$message.warning(res.msg)
              }
            })
            .catch(() => {
              this.$message.warning('网络异常')
            })
            .then(() => {
              hide()
            })
        },
      })
    },
    onRemove(item) {
      const hide = this.$message.loading('删除中...')
      delData({ id: item.id })
        .then((res) => {
          if (res.code == 0) {
            this.$message.success(res.msg)
            this.$refs.table.refresh(1)
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(() => {
          this.$message.warning('网络异常')
        })
        .then(() => {
          hide()
        })
    },
    onOk() {
      this.$refs.modalForm.validate((valid) => {
        if (valid) {
          if (this.form.to_store_ids.indexOf(this.form.from_store_id) > -1) {
            this.$message.warning('被同步店铺中不能包含来源店铺')
            return
          }
          this.loading = true
          const form = {
            ...this.form,
            id: this.isNew ? '' : this.form.id,
          }
          saveData(form)
            .then((res) => {
              if (res.code == 0) {
                this.$message.success(res.msg)
                this.visible = false
                this.$refs.table.refresh(1)
              } else {
                this.$message.error(res.msg)
              }
            })
            .catch(() => {
              this.$message.error('保存失败')
            })
            .then(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    onSelectStore() {
      this.$nextTick(() => {
        const el = this.$refs.toolsStore
        el.visible = true
      })
    },
    selectStore(ids, list) {
      this.$nextTick(() => {
        this.form.to_store_ids = ids
        this.currentItem.to_store_ids = ids
        this.currentItem.to_store_names = list
      })
    },
  },
}
</script>

<style lang="less" scoped></style>
